package com.yixq.controller;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yixq.service.HttpRequestService;
import com.yixq.util.ExcelUtil;
import com.yixq.util.ResponseUtil;
import com.yixq.vo.DataResponseVo;


@Controller
public class FkStatusQueryController {

	private static Logger logger = LoggerFactory.getLogger(FkStatusQueryController.class);



	@RequestMapping("/fk_status_query")
	public String fkStatusQuery(Map<String, Object> map) {
		return "fk_status_query";

	}
	
	
	@RequestMapping("fileUpload")
	@ResponseBody
	public String fileUpload(@RequestParam("fileName") MultipartFile file,
			HttpServletResponse res) {
		String fileName = file.getOriginalFilename();
		try {
			if (!fileName.matches("^.+\\.(?i)(xls)$")
					&& !fileName.matches("^.+\\.(?i)(xlsx)$")) {
				throw new Exception("上传文件格式不正确");
			}
			batchImport(fileName, file, res);
		} catch (Exception e) {
			logger.error("",e);
		}
		return "查询失败";

	}

	public boolean batchImport(String fileName, MultipartFile file,
			HttpServletResponse res) throws Exception {
		List<DataResponseVo> dataList = new ArrayList<DataResponseVo>();
		
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		InputStream is1 = file.getInputStream();
		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is1);
		} else {
			wb = new XSSFWorkbook(is1);
		}
		Sheet sheet = wb.getSheetAt(0);
		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
			DataResponseVo vo = new DataResponseVo();
			Row row = sheet.getRow(r);
			if (row == null) {
				continue;
			}
			String assetID = "0";
			try {
				assetID = String.valueOf(row.getCell(0).getNumericCellValue());
				assetID = assetID.substring(0, assetID.indexOf("."));
			} catch (Exception e) {
				logger.error("",e);
			}
			
			try{
				if(assetID.equals("0")){
					assetID =row.getCell(0).getStringCellValue();
				}
			}catch(Exception e){
				logger.error("",e);
			}
			
			String status = "-100";
			try {
				//status = HttpsUtil.getRequestStatus(assetID, vo);
				status = HttpRequestService.getRequestStatus(assetID, vo);
			} catch (Exception e) {
				logger.error("",e);
			}
			vo.setAssetID(assetID);
			vo.setStatus(status);
			dataList.add(vo);
		}
		String columnNames[] = { "AssetID", "status", "statusDesc", "response" };
        String keys[] = { "AssetID", "status", "statusDesc", "response" };;//map中的key

		try {
			List<Map<String, Object>>  listMap=createExcelRecord(dataList);
			
			Workbook wbExport =ExcelUtil.createWorkBook(listMap, keys, columnNames);
			
			ResponseUtil.export(res, wbExport,"放款状态批量查询" + Calendar.getInstance().getTimeInMillis() + ".xls");
		
		} catch (IOException e) {
			logger.error("",e);
		}
		return false;
	}

	
	private List<Map<String, Object>> createExcelRecord(List<DataResponseVo> list) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "放款状态");
        listmap.add(map);
        DataResponseVo vo = null;
        for (int j = 0; j < list.size(); j++) {
        	vo = list.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("AssetID", vo.getAssetID());
            mapValue.put("status", vo.getStatus());
            mapValue.put("statusDesc", vo.getStatusDesc());
            mapValue.put("response", vo.getResponse());
            listmap.add(mapValue);
        }
        return listmap;
    }
}